package xyz.ranyh.jobclient.fragment;

import android.app.ListFragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import xyz.ranyh.jobclient.R;
import xyz.ranyh.jobclient.http.GetStarJobTask;
import xyz.ranyh.jobclient.util.JobBean;
import xyz.ranyh.jobclient.util.StarListAdapter;

/**
 * A simple {@link ListFragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FavorityFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FavorityFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FavorityFragment extends ListFragment {
    private GetStarJobTask getStarListTask;
    private OnFragmentInteractionListener mListener;
    private ArrayList<JobBean> jobs = new ArrayList<JobBean>();
    ;
    private StarListAdapter starListAdapter;
    private WebViewListener webViewListener;
    private SwipeRefreshLayout swipeRefreshLayout;
    public void setWebViewListener(WebViewListener webViewListener) {
        this.webViewListener = webViewListener;
    }

    public interface WebViewListener {
        void initWebView(String url, String title);
    }
    public WebViewListener getWebViewListener() {
        return webViewListener;
    }

    public FavorityFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment FavorityFragment.
     */
    public static FavorityFragment newInstance() {
        FavorityFragment fragment = new FavorityFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        jobs = new ArrayList<JobBean>();
        starListAdapter = new StarListAdapter(getActivity(), jobs);
        starListAdapter.setListener(new StarListAdapter.ViewClickListener() {
            @Override
            public void onClick(int i, View view, String url) {
                webViewListener.initWebView(url,jobs.get(i).getTitle());
            }
        });
        getStarJob();

        this.setListAdapter(starListAdapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.favorite, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        return view;
//        return inflater.inflate(R.layout.favorite, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private void getStarJob() {
        getStarListTask = new GetStarJobTask(jobs);
        getStarListTask.setGetJoblistener(new GetStarJobTask.GetJoblistener() {
            @Override
            public void onSuccess(JSONObject res) {
//                JSONArray jobList = null;
//                try {
//                    Log.d("ddddddddd", ""+jobs.size());
//                    jobList = res.getJSONArray("jobs");
//                    for (int i = 0;i < jobList.length();i++) {
//                        JSONObject item = (JSONObject)jobList.get(i);
//
//                        JobBean mJB = new JobBean();
//                        mJB.setId(item.getInt("id"));
//                        mJB.setTitle(item.getString("title"));
//                        mJB.setUrl(item.getString("url"));
//                        mJB.setRefUrl(item.getString("ref_url"));
//                        mJB.setTags(item.getString("tags"));
//                        mJB.setFollowerCount(item.getInt("follower_count"));
//                        mJB.setOpenDate(item.getString("open_date"));
//                        mJB.setPublishedDate(item.getString("published_date"));
//                        mJB.setOpenDateInt(item.getInt("open_date_int"));
//
//                        jobs.add(mJB);
//                    }
//                    Log.d("ddddddddd", ""+jobs.size());
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
                starListAdapter.notifyDataSetChanged();
                if (jobs.size() > 0 && swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getActivity(),"刷新成功",Toast.LENGTH_SHORT).show();
                }
            }
        });
        getStarListTask.execute();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
    private void refresh() {
        jobs.clear();
        starListAdapter.notifyDataSetChanged();
        getStarJob();
    }
}
